<template>
  <el-dialog title="分配角色" :visible="showRoleDialog" @close="close" @open="onOpen">
    <!-- el-checkbox-group选中的是 当前用户所拥有的角色  需要绑定 当前用户拥有的角色-->
    <el-checkbox-group v-model="checkList">
      <!-- 选项 -->
      <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="onSave">确定</el-button>
        <el-button size="small" @click="close">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRolesList } from '@/api/roles.js'
import { getUserInfoById } from '@/api/user.js'
import { saveEmployeesAssignRole } from '@/api/employees.js'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roles: [],
      // 双向绑定记录选中项
      checkList: []
    }
  },
  created() {

  },
  methods: {
    async loadRolesList() {
      const { rows } = await getRolesList()
      console.log(rows)
      this.roles = rows
    },
    async loadEmployeesRoles() {
      // 员工id
      const res = await getUserInfoById(this.userId)
      this.checkList = res.roleIds
    },
    onOpen() {
      this.loadRolesList()
      this.loadEmployeesRoles()
    },
    async onSave() {
      if (!this.checkList.length) return this.$message.error('请选择必要的角色')
      await saveEmployeesAssignRole({
        id: this.userId,
        roleIds: this.checkList
      })
      this.$message.success('分配角色成功')
      this.close()
    },
    close() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>

